package com.itmk.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

/**
 * 阿里云 OSS 工具类
 */
@Component
@Slf4j
public class AliOSSUtils {

    private final String endpoint = "https://oss-cn-beijing.aliyuncs.com";
    private final String accessKeyId = "LTAI5t9BiNKJK1Su5pm6RUXk";
    private final String accessKeySecret = "Xz1EgUy9nG62gxsSxBEscCAU7bEeiH";
    private final String bucketName = "sddrjack";

   // @Value("${aliyun.oss.file.folder}")
    //private String folder;
    /*public void download(String name, HttpServletResponse response) throws IOException {
       String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + name;
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        OSSObject ossObject = ossClient.getObject(bucketName, name);
        InputStream inputStream = ossObject.getObjectContent();
        StringBuilder objectContent = new StringBuilder();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        ServletOutputStream outputStream = response.getOutputStream();
        response.setContentType("image/jpeg");
        while (true) {
            String line = reader.readLine();
            if (line == null)
                break;
            objectContent.append(line);
          //  ServletOutputStream outputStream = response.getOutputStream();
            //response.setContentType("image/jpeg");
        }
        inputStream.close();
        System.out.println("Object：" + name + "的内容是：" + objectContent);
        log.info("Object{}",objectContent);



    }*/


        /**
         * 通过OSS下载文件到输出流，并返回文件名
         *
         * @param objectName OSS对象名称
         * @param response   HTTP响应对象
         * @throws Exception
         */
        public void downloadFileFromOSS(String objectName, HttpServletResponse response) throws Exception {
            String fileName = objectName.substring(objectName.lastIndexOf("/") + 1);
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            OSSObject ossObject = ossClient.getObject(new GetObjectRequest(bucketName, objectName));
            InputStream inputStream = ossObject.getObjectContent();
            OutputStream outputStream = response.getOutputStream();
            byte[] buffer = new byte[10240];
            int len = 0;
            while ((len = inputStream.read(buffer, 0, 10240)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            inputStream.close();
            response.setContentType("image/jpeg");
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
        }


    /**
     * 实现上传图片到OSS
     */

    public String upload(MultipartFile file) throws IOException {
        // 获取上传的文件的输入流
        InputStream inputStream = file.getInputStream();

        // 避免文件覆盖
        String originalFilename = file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));

        //上传文件到 OSS
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, fileName, inputStream);

        //文件访问路径
        String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;
        // 关闭ossClient
        ossClient.shutdown();
        return url;// 把上传到oss的路径返回
    }

}
